<!--
  * 商品分类
  *
-->
<template>
  <a-card class="tree-container" :style="{ height: appConfigStore.getLayoutContentClientRect.height + 'px' }">
    <template #title>
      <div style="display: flex; align-items: center; justify-content: space-between; width: 100%">
        <span style="font-size: 14px">商品分类</span>
      </div>
    </template>
    <a-tree style="height: 65vh; overflow-y: auto" v-if="!_.isEmpty(categoryTreeData)" v-model:selectedKeys="selectedKeys" :treeData="categoryTreeData" autoExpandParent :fieldNames="{ title: 'cate_name', key: 'key', value: 'id' }" @select="onSelect">
      <template #title="{ cate_name }">
        <span>{{ cate_name }}</span>
      </template>
    </a-tree>
  </a-card>
</template>
<script setup lang="ts">
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { goodsApi } from '@/api/business/shopping-mall/product-api'
import { useAppConfigStore } from '@/store/modules/app-store'
import { treeToList } from '@/utils/tree-util'
import eventEmitter from '@/lib/event-emitter'
import customEventName from '@/views/business/shopping/product/product-event-name'
const appConfigStore = useAppConfigStore()

const emit = defineEmits(['select-category'])
// ----------------------- 分类树的展示 ---------------------
// 分类树形数据
const categoryTreeData = ref<any[]>([])
// 查询分类列表并构建仓库树
const selectedKeys = ref<number[]>([0])

// 查询分类列表并构建 分类树
const queryData = async () => {
  try {
    const res = await goodsApi.queryCategoryList() // 查询分类列表
    const list = [
      {
        id: 0,
        cate_name: '全部'
      }
    ]
    if (res.data.length > 0) {
      list.push(...res.data)
    }
    categoryTreeData.value = list
  } catch (error) {
    message.error(error.msg)
  }
}

eventEmitter.on(customEventName.QueryCategoryList, queryData)
onMounted(queryData)

// 选中分类
const onSelect = (keys: [], info: any) => {
  selectedKeys.value = keys
  const cate_id = treeToList([info.node.dataRef])
    .map(({ id }) => id)
    .join(',')
  eventEmitter.emit(customEventName.QueryProductList, { cate_id: cate_id })
}
</script>
<style scoped lang="less">
:deep(.ant-card-body) {
  padding-top: 10px;
}
.tree-container {
  height: 100%;
  overflow-y: auto;
  overflow: hidden;
  .tree {
    height: 618px;
    margin-top: 10px;
    overflow-x: hidden;
    overflow-y: auto;
  }

  .sort-flag-row {
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .sort-span {
    margin-left: 5px;
  }
  .no-data {
    margin: 10px;
  }
}
</style>
